import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',// 用户头像
    roles: [], // 角色权限控制按钮显示
    menus: [] // 菜单权限
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  }, SET_TOKEN: (state, token) => {
    state.token = token
  }, SET_NAME: (state, name) => {
    state.name = name
  }, SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }, SET_ROLES: (state, roles) => {
    state.roles = roles // 角色权限
  }, SET_MENUS: (state, menus ) => {
    state.menus = menus // 菜单权限
  },SET_PERMISSIONS(state,permissions){
    state.permissions = permissions
  },SET_user_id(state,user_id){
    state.user_id = user_id
  },SET_account(state,account){
    state.account = account
  },SEt_data(state,data){
    state.data = data
  }
}

const actions = {
  // 查询
  queryuser() {

  },
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    let formData = { username: username.trim(), password: password }
    return new Promise((resolve, reject) => {
      login(formData).then(response => {
        const token = response.data.data
        commit('SET_TOKEN', token) // vuex存储token
        setToken(token) // cookie存储token
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response.data
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { user_name, roles, menus,permissions,user_id,account,avatar } = data
        commit('SET_NAME', user_name)// 用户名
        console.log(data)
        commit('SET_ROLES', roles)// 角色权限
        commit('SET_MENUS', menus)// 菜单权限
        commit('SET_PERMISSIONS',permissions)
        commit('SET_user_id',user_id)
        commit('SET_account',account)
        commit('SET_user_name',user_name)
        commit('SET_AVATAR',avatar)
        commit('SEt_data',data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => { // 如果后端有退出接口写在下面即可，这里直接退出也没问题
      removeToken() // 必须先移除token
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true, state, mutations, actions
}
